package com.zjj.lbw.spring6.service;

import com.zjj.lbw.spring6.entity.Role;
import com.zjj.lbw.spring6.entity.User;
import com.zjj.lbw.spring6.mapper.RoleMapper;
import com.zjj.lbw.spring6.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

//@Component
public class ZjjUserService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;


    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {

        // 1. 查询用户
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 2. 查询角色并转换为GrantedAuthority
        List<Role> roles = roleMapper.selectRolesByUserId(user.getId());
        List<GrantedAuthority> authorities = roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRoleName()))
                .collect(Collectors.toList());

        user.setAuthorities(authorities);
        return user;
    }
}
